<template>
	<div class="countdown">
		<div class="description">{{ description }}</div>
		<div class="timer">
			<span class="days">{{ days }}</span>天
			<span class="time">{{ hours }}</span>:{{ minutes }}:{{ seconds }}
		</div>
	</div>
</template>

<script>
	export default {
		name: 'ActCountdown',
		props: {
			description: {
				type: String,
				default: '距离活动结束'
			},
			endTime: {
				type: [Number, Date, String], // 添加 String 类型支持
				required: true
			}
		},
		data() {
			return {
				days: 0,
				hours: '00',
				minutes: '00',
				seconds: '00',
				timer: null
			}
		},
		mounted() {
			this.updateTime()
			this.timer = setInterval(this.updateTime, 1000)
		},
		beforeDestroy() {
			clearInterval(this.timer)
		},
		methods: {
			updateTime() {
				// 处理字符串类型的 endTime，转换为 ISO 格式
				let endTime = this.endTime
				if (typeof endTime === 'string') {
					endTime = endTime.replace(' ', 'T') // 替换第一个空格为 T
				}
				const end = new Date(endTime).getTime()
				const now = Date.now()
				const diff = end - now

				if (diff <= 0) {
					clearInterval(this.timer)
					this.days = 0
					this.hours = '00'
					this.minutes = '00'
					this.seconds = '00'
					return
				}

				const days = Math.floor(diff / (1000 * 60 * 60 * 24))
				const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
				const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
				const seconds = Math.floor((diff % (1000 * 60)) / 1000)

				this.days = days
				this.hours = hours.toString().padStart(2, '0')
				this.minutes = minutes.toString().padStart(2, '0')
				this.seconds = seconds.toString().padStart(2, '0')
			}
		}
	}
</script>

<style scoped>
	/* 样式保持不变 */
	.countdown {
		width: 360px;
		margin: 0 7.5px 7.5px;
		background-color: #FFF;
		border-radius: 7px;
		display: flex;
		flex-direction: row;
		border: 1px solid #eee;
		text-align: center;
		padding: 8px 0px;
		gap: 8px;
		align-items: center;
		justify-content: center;
	}

	.description {
		font-size: 14px;
	}

	.timer {
		font-size: 16px;
		font-weight: bold;
		color: #FF4444;
	}


	.days {
		/*
		color: #f44336;*/
	}

	.time {
		/*
		color: #2196f3;*/
	}
</style>
